import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router"; // 引入路由实例（需根据项目路径调整）
import { useUserStore } from "@/store";
// 创建 axios 实例
const axiosRequestInstance = axios.create({
  timeout: 5000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// ====== 请求拦截器（使用 InternalAxiosRequestConfig 类型） ======
axiosRequestInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 关键：用 InternalAxiosRequestConfig 代替 AxiosRequestConfig
    const token = sessionStorage.getItem("JWTTOKEN");
    if (token && config.headers) {
      // 确保 headers 不为 undefined（类型安全处理）
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// ====== 响应拦截器：处理 401 错误 ======
axiosRequestInstance.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    console.log("原始响应结构:", response.data);

    // 兼容两种返回格式
    if (response.data && response.data.data) {
      return response.data.data;
    } else if (response.data && response.data.fileName) {
      return response.data;
    }
    return response.data;
  },
  async (error) => {
    if (error._isHandled) return Promise.reject(error);
    error._isHandled = true;

    if (error.response) {
      const { status } = error.response;

      // ====== 处理 401 状态码 ======
      if (status === 401) {
        // 清除无效令牌
        sessionStorage.removeItem("JWTTOKEN");

        // 提示用户并跳转登录页（可根据需求改为自动刷新令牌）
        ElMessageBox.confirm("您的登录已过期，请重新登录", "登录过期", {
          confirmButtonText: "去登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 跳转登录页，并记录当前路径（登录后可返回原页面）
          const userStore = useUserStore();
          userStore.logout();
          router.push({
            path: "/login",
            query: { redirect: router.currentRoute.value.fullPath },
          });
        });
        return Promise.reject(error);
      }

      // 其他状态码处理
      switch (status) {
        case 400:
          ElMessage.error("操作失败：参数错误");
          break;
        case 403:
          ElMessage.error("没有权限访问该资源");
          break;
        case 404:
          ElMessage.error("接口不存在");
          break;
        case 500:
          ElMessage.error("服务器内部错误");
          break;
        default:
          ElMessage.error(`请求失败（状态码：${status}）`);
      }
    } else {
      ElMessage.error("请求服务器失败：网络错误");
    }
    return Promise.reject(error);
  }
);

export default {
  // 明确指定返回类型为 Promise<UserInfo>
  login(phone: string, password: string): Promise<any> {
    return axiosRequestInstance.post("/api/user/login", { phone, password });
  },
  changePassword(id: string, password: string) {
    return axiosRequestInstance.post("/api/user/changePassword", { id, password });
  },
  getCategoryList(keyword: string = "") {
    return axiosRequestInstance.get("/api/Category/list", {
      params: { keyword },
    });
  },
  changeCategoryState(id: string) {
    return axiosRequestInstance.post("/api/Category/changeState", id);
  },
  createCategory(name: string, weight: number, cover: string, state: number = 1) {
    return axiosRequestInstance.post("/api/Category/create", { name, weight, cover, state });
  },
  updateCategory(id: string, name: string, weight: number, cover: string, state: number = 1) {
    return axiosRequestInstance.post("/api/Category/update", {
      id,
      name,
      weight,
      cover,
      state,
    });
  },

  uploadImages(file: File) {
    const formData = new FormData();
    formData.append("file", file);
    return axiosRequestInstance.post("/resource/uploadImage", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },
  getCourseList(keyword: string = "", categoryId: string = "") {
    return axiosRequestInstance.get("/api/Course/list", {
      params: { keyword, categoryId },
    });
  },
  changeCourseState(id: string) {
    return axiosRequestInstance.post("/api/Course/changeState", id);
  },
  createCourse(
    name: string,
    description: string,
    cover: string,
    duration: string,
    state: number,
    categoryId: string
  ) {
    return axiosRequestInstance.post("/api/Course/create", {
      name,
      description,
      cover,
      duration,
      state,
      categoryId,
    });
  },
  updateCourse(
    id: string,
    name: string,
    description: string,
    cover: string,
    duration: string,
    state: number,
    categoryId: string
  ) {
    return axiosRequestInstance.post("/api/Course/update", {
      id,
      name,
      description,
      cover,
      duration,
      state,
      categoryId,
    });
  },
  getPracticalCourseList(keyword: string = "", categoryId: string = "") {
    return axiosRequestInstance.get("/api/PracticalCourse/list", {
      params: { keyword, categoryId },
    });
  },
  changePracticalCourseState(id: string) {
    return axiosRequestInstance.post("/api/PracticalCourse/changeState", id);
  },
  createPracticalCourse(
    title: string,
    description: string,
    cover: string,
    difficulty: string,
    duration: string,
    state: number,
    categoryProjectId: string
  ) {
    return axiosRequestInstance.post("/api/PracticalCourse/create", {
      title,
      description,
      cover,
      difficulty,
      duration,
      state,
      categoryProjectId,
    });
  },
  updatePracticalCourse(
    id: string,
    title: string,
    description: string,
    cover: string,
    difficulty: string,
    duration: string,
    state: number,
    categoryProjectId: string
  ) {
    return axiosRequestInstance.post("/api/PracticalCourse/update", {
      id,
      title,
      description,
      cover,
      difficulty,
      duration,
      state,
      categoryProjectId,
    });
  },
  getWxUserList(keyword: string) {
    return axiosRequestInstance.get("/api/WxUser/wxUserList", { params: { keyword } });
  },
  getWxUserLoginLog(userId: string) {
    return axiosRequestInstance.get("/api/WxUser/wxUserLoginLog", { params: { userId } });
  },
  getWxUserLearningRecord(userId: string) {
    return axiosRequestInstance.get("/api/WxUser/wxUserLearningRecord", { params: { userId } });
  },
  getWxUserStudyPlan(userId: string) {
    return axiosRequestInstance.get("/api/WxUser/wxUserStudyPlan", { params: { userId } });
  },
  changeWxUserState(userId: string) {
    return axiosRequestInstance.post("/api/WxUser/changeWxUserState", userId);
  },
  getBankList(keyword: string = "", categoryId: string = "") {
    return axiosRequestInstance.get("/api/InterviewGuide/list", {
      params: { keyword, categoryId },
    });
  },
  changeBankState(id: string) {
    return axiosRequestInstance.post("/api/InterviewGuide/changeState", id);
  },
  createBank(title: string, categoryId: string, state: number = 1, categoryName: string) {
    return axiosRequestInstance.post("/api/InterviewGuide/create", {
      title,
      categoryId,
      state,
      categoryName,
    });
  },
  updateBank(id: string, title: string, categoryId: string, state: number, categoryName: string) {
    return axiosRequestInstance.post("/api/InterviewGuide/update", {
      id,
      title,
      categoryId,
      state,
      categoryName,
    });
  },
  getQuestionList(bankId: string) {
    return axiosRequestInstance.get("/api/InterviewGuide/questionList", {
      params: { bankId },
    });
  },
  changeQuestionState(id: string) {
    return axiosRequestInstance.post("/api/InterviewGuide/questionChangeState", id);
  },
  createQuestion(bankId: string, topic: string, answer: string, state: number = 1) {
    return axiosRequestInstance.post("/api/InterviewGuide/questionCreate", {
      bankId,
      topic,
      answer,
      state,
    });
  },
  updateQuestion(id: string, bankId: string, topic: string, answer: string, state: number) {
    return axiosRequestInstance.post("/api/InterviewGuide/questionUpdate", {
      id,
      bankId,
      topic,
      answer,
      state,
    });
  },
  getArticleList(keyword: string = "", categoryId = "") {
    return axiosRequestInstance.get("/api/Article/list", {
      params: { keyword, categoryId },
    });
  },
  changeArticleState(id: string) {
    return axiosRequestInstance.post("/api/Article/changeState", id);
  },
  createArticle(
    title: string,
    content: string,
    author: string,
    publishDate: string,
    coverUrl: string,
    state: number,
    categoryArticleId: string
  ) {
    return axiosRequestInstance.post("/api/Article/create", {
      title,
      content,
      author,
      publishDate,
      coverUrl,
      state,
      categoryArticleId,
    });
  },
  updateArticle(
    id: string,
    title: string,
    content: string,
    author: string,
    publishDate: string,
    coverUrl: string,
    state: number,
    categoryArticleId: string
  ) {
    return axiosRequestInstance.post("/api/Article/update", {
      id,
      title,
      content,
      author,
      publishDate,
      coverUrl,
      state,
      categoryArticleId,
    });
  },
  getCommunityList(keyword: string = "", categoryId: string = "") {
    return axiosRequestInstance.get("/api/Community/list", {
      params: { keyword, categoryId },
    });
  },
  changeCommunityState(id: string) {
    return axiosRequestInstance.post("/api/Community/changeState", id);
  },
  getCommentList(circleId: string) {
    return axiosRequestInstance.get("/api/Community/commentList", {
      params: { circleId },
    });
  },
  deleteComment(id: string) {
    return axiosRequestInstance.post("/api/Community/deleteComment", id);
  },
};
